package com.practice.Socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private Integer threadNum = 0;
    private ServerProcessor processor = new ServerProcessor();

    public class serverProcessor implements Runnable {
        private Socket socket;
        private Integer no;
        private Integer closeInfo = 0;

        public serverProcessor(Socket socket, Integer no) {
            this.socket = socket;
            this.no = no;
        }


        @Override
        public void run() {
            try {
                System.out.println("客户端 No." + no + " 连接成功");
                processor.getPrintWriterHashMap().put(no + "", new PrintWriter(socket.getOutputStream()));
                new Thread(processor.new SocketReceiver(socket.getInputStream(), no, closeInfo, "服务器")).start();
                while (true) {
                    Thread.sleep(1000);
                    if (closeInfo == 1)
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void accept() throws IOException {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8081);
            new Thread(processor.new SocketSender()).start();
            System.out.println("服务器启动成功");
            while (true) {
                new Thread(new serverProcessor(server.accept(), threadNum++)).start();
            }
        } catch (Exception e) {
            System.out.println("服务器accept失败");
            e.printStackTrace();
        } finally {
            if (server != null) {
                server.close();
            }

        }
    }

    public static void main(String[] args) throws IOException {
        Server s = new Server();
        s.accept();
    }

}
